package org.example.aop;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.anno.LogOperation;
import org.example.anno.LoginOperation;
import org.example.mapper.EmpMapper;
import org.example.pojo.Emp;
import org.example.pojo.EmpLoginLog;
import org.example.pojo.LoginInfo;
import org.example.pojo.Result;
import org.example.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class LoginAspect {
    @Autowired
    private EmpMapper empMapper;

    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, LoginOperation log) throws Throwable {
        Object[] args = joinPoint.getArgs();
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();
        // 当前时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long costTime = endTime - startTime;
        // 获取方法参数
        Emp emp = null;
        for (Object arg : args) {
            if (arg instanceof Emp) {
                emp = (Emp) arg;
                break;
            }
        }

        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setUsername(emp.getUsername());
        empLoginLog.setPassword(emp.getPassword());
        empLoginLog.setLoginTime(LocalDateTime.now());
        empLoginLog.setIsSuccess((short) (result.toString().contains("success") ? 1 : 0));
        System.out.println(result);
        Result apiResult = (Result) result;
        if (apiResult.getData() instanceof LoginInfo) {
            LoginInfo loginInfo = (LoginInfo) apiResult.getData();
            empLoginLog.setJwt(loginInfo.getToken());
        }
        empLoginLog.setCostTime(costTime);
        empMapper.save(empLoginLog);
        return result;
    }
}
